<?php
namespace app\api\controller;

use app\common\logic\Logic;
use app\common\model\MyCar;
use app\common\service\App;
use app\common\service\ChatService;
use rongyun\api\RongCloud;
use think\Cache;
use think\Controller;
use think\Db;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use think\Exception;
use think\Log;
use think\Request;
use wheat\Wheat;

class Base extends Controller
{




    public function _initialize()
    {

//        dd(input());exit;
//        $ip = request()->ip();
//        $num = Cache::get($ip);
//        if (!empty($num)){
//            if ($num > 60) api_return(0,'访问过于频繁,请稍后重试');
//            Cache::inc($ip);
//        }else{
//            Cache::set($ip,1,60);
//        }
    }

    /**
     * @param string $url 文件第三方完整地址
     * @return array
     * $array[code] 查询状态 1=>查询成功  0查询失败
     * $array[msg] 提示信息
     * $array[size] 查询出的文件大小 单位MB
     * $array[data] 第三方返回的信息  用于调试
     */
    protected function fileInfo($url = '')
    {
        $array['code'] = 0;
        if (empty($url)){
            $array['msg'] = '文件不存在';
        } else{
            $key = substr($url,(strripos($url,'/')+1));
            $accessKey = config('qiniu.ACCESSKEY');
            $secretKey = config('qiniu.SECRETKEY');
            $bucket = config('qiniu.bucket');
            $auth = new Auth($accessKey, $secretKey);
            $config = new Config();
            $bucketManager = new BucketManager($auth, $config);
            list($fileInfo, $err) = $bucketManager->stat($bucket,$key);
            if ($err) {
                $array['msg']  = '文件信息查询失败';
                $array['data'] = $err;
            } else {
                $array['code'] = 1;
                $array['msg']  = '文件信息查询成功';
                $array['size'] = round($fileInfo['fsize']/1024/1024,2);
                $array['data'] = $fileInfo;
            }
        }
        return $array;
    }

    /**
     * 用户签到方法
     * @param int $user_id 用户id
     */
    protected static function userSignIn( $user_id)
    {
        $data = Db::name('sign')->where('user_id',$user_id)->select();
        if(count($data) == 0)  //没有该用户的签到记录
        {
            Db::name('sign')->insert(['times'=>date('Y-m-d H:i:s'),'user_id'=>$user_id,'days'=>1]);
            return 1;
        }
        else
        {
            //判断今天是否签到
            $todayBegin = date('Y-m-d'." 00:00:00");
            $todayEnd   = date('Y-m-d'." 23:59:59");
            $isExit     = Db::name('sign')->field('times')->where(['user_id'=>$user_id])->where('times','between',[$todayBegin,$todayEnd])->select();
            if(count($isExit) == 1)   //今日已签到
            {
                return 0;
            }
            else    //今日未签到
            {
                $times = Db::name('sign')->where('user_id',$user_id)->field('times')->select();
                $time  = strtotime($times[0]['times']);

                if((time()-$time > 24*60*60))       //上次签到时间大于24小时，连续签到天数清零
                {
                    Db::name('sign')->where('user_id',$user_id)->update(['days'=>1]);
                    $days = 1;
                }
                else     //上次签到时间小于24小时，连续签到次数加1
                {
                    Db::name('sign')->where('user_id',$user_id)->setInc('days');
                    $days = $isExit['days'];
                }
                //更新上次签到时间和签到积分
                Db::name('sign')->where('user_id',$user_id)->update(['times'=>date('Y-m-d H:i:s')]);
                return $days;
//                $sqldate = date('m',$time);    //上次签到日期的月份
//                $nowdate = date('m',time());  //当前月份
//                //记录本次签到日期
//                if($sqldate != $nowdate)  //上次签到日期与本次签到日期月份不一样
//                {
//                    $oldtime = $times[0]['times'];
//                    $onetime=date("Y-m-d H:i:s", strtotime("-1 month"));  //获取前1个月的时间，获取格式为2016-12-30 13:26:13
//                    $twotime=date("Y-m-d H:i:s", strtotime("-2 month"));  //获取前2个月的时间
//                    $threetime=date("Y-m-d H:i:s", strtotime("-3 month"));  //获取前3个月的时间
//
//                    $rs = Db::name('sign')->where('user_id',$user_id)->field('one,two,three')->select();
//
//                    if($oldtime < $onetime && $oldtime >= $twotime)     //月份间隔 大于1个月，小于2个月
//                    {
//                        $one =  date('d',time());
//                        $two = $rs[0]['one'];
//                        $three = $rs[0]['two'];
//                    }
//                    elseif($oldtime < $twotime && $oldtime >= $threetime) //月份间隔 大于2个月，小于3个月
//                    {
//                        $one =  date('d',time());
//                        $two = '';
//                        $three = $rs[0]['one'];
//                    }
//                    elseif($oldtime < $threetime)  //月份间隔 大于3个月
//                    {
//                        $one =  date('d',time());
//                        $two = '';
//                        $three = '';
//                    }
//                    $query3 = Db::name('sign')->where('user_id',$user_id)->update(['one'=>$one,'two'=>$two,'three'=>$three]);
//                }
//                else  //上次签到日期与本次签到日期月份一样
//                {
//                    $one = Db::name('sign')->where('user_id',$user_id)->field('one')->select();
//                    $arr[] = $one[0]['one'];
//                    $arr[] = date('d',time());
//                    $newones = implode(",",$arr);
//                    $query3 = Db::name('sign')->where('user_id',$user_id)->update(['one'=>$newones]);
//                }
            }
        }
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $room_id
     * 获取房间信息
     */
    public function roomInfo($room_id,$field = '',$cache = 3)
    {
        $map['room_id'] = $room_id;
        $map['status']  = 1;

        $data =  Db::name('room')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    public static function StaticRoomInfo($room_id,$field = '',$cache = 3)
    {
        $map['room_id'] = $room_id;
        $map['status']  = 1;

        $data =  Db::name('room')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $field
     * @param bool $array 是否返回数组
     * @param int $cache
     * 获取扩展文本信息
     */
    public static function getExplain($field,$array = false,$cache = 30)
    {
        $rows = Db::name('explain')->cache($cache)->select();
        $data = array_key($rows,'field');
        if (strstr($field,',')){
            $array = true;
        }
        if ($array){
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v]['content'];
            }
            return $array;
        }
        return $data[$field]['content'];
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户扩展信息
     */
    protected function userExtra($field = '',$user_id = null,$cache = 3){
        if ($user_id){
            if (!is_numeric($user_id)){
                $user_id = dehashid($user_id);
                if (!is_numeric($user_id)){
                    api_return(0,'用户id错误');
                }
            }
            $map['user_id'] = $user_id;
        }else{
            $map['user_id'] = $this->user_id;
        }
        $data =  Db::name('user_extend')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户扩展信息
     */
    public static function staticExtra($field = '',$user_id,$cache = 3){

        $map['user_id'] = $user_id;
        $data =  Db::name('user_extend')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }



    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 静态获取用户信息
     */
    public static function staticInfo($field = '',$user_id = null,$cache = 3){

        if ($user_id){

            $map['user_id'] = $user_id;

        }else{
            return '';
        }

        $data =  Db::name('users')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }

    }
    public static function followStatus($user_id, $follow_user):int
    {
        $map['user_id']     = $user_id;
        $map['follow_user'] = $follow_user;

        return Db::name('user_follow')->where($map)->value('status')??0;
    }


    public static function isFriend( $user_id, $follow_user):int
    {
        $map['user_id']     = $user_id;
        $map['follow_user'] = $follow_user;
        $map['status']      = 1;
        return $follow_id = Db::name('user_friend')->where($map)->value('status')??0;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 查询是否关注房间 可用于判断权限
     */
    public static function roomPower($room_id,$user_id)
    {
        $follow['room_id'] = $room_id;
        $follow['user_id'] = $user_id;
        return Db::name('room_follow')->where($follow)->cache(3)->value('status')??0;
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 检查贵族是否有效  有效返回贵族id  无效返回0
     *$data => ['user_id','noble_id','noble_time']
     */
    public static function checkNoble($data)
    {

        if ($data['noble_time'] < time()){
            //TODO 创建的聊天房间设为过期
            //如果贵族已过期一个月以上 清除用户贵族id 和贵族过期时间
            if ($data['noble_time'] < time() + 3600*24*31){
                if (!is_numeric($data['user_id'])){
                    $user_id = dehashid($data['user_id']);
                }else{
                    $user_id = $data['user_id'];
                }
                if (empty($user_id) || !is_numeric($user_id)){
                    api_return(0,'checkNoble user_id错误');
                }

                Db::name('user_extend')->where('user_id',$user_id)->update(['noble_id'=>0,'noble_time'=>0]);
            }

            return 0;
        }
        return $data['noble_id'];
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 退出房间
     */


    public static function outRoomFunc($user_id,$room_id)
    {
        if (!$room_id){
            return false;
        }
        delHot($room_id);
        $roomInfo = self::StaticRoomInfo($room_id);
        //用户上麦成功 或在排麦中 清除排麦数据
        $wheat = Wheat::wheat($room_id);
        $refresh = false;
        $hash = hashid($user_id);
        foreach ($wheat as $k => $v){
//            //电台房间  主播下麦清空麦序
//            if ($roomInfo['type'] == 1){
//                if ($wheat[0]['user_id'] = $hash){
//                    Wheat::wheatInit($room_id);
//                    $refresh = true;
//                    goto refresh;
//                }
//            }
//
//            //娱乐和聊天房间  房主不下麦
//            if ($roomInfo['type'] == 2 || $roomInfo['type'] == 4){
//                if ($roomInfo['user_id'] == $user_id){
//                    continue;
//                }
//            }

            if ($v['user_id'] == $hash){
                //在麦序上清除麦序信息发送房间麦序推送且循环不继续执行
                $refresh = true;
                $wheat[$k]['user_id']    = "0";
                $wheat[$k]['header_img'] = "";
                $wheat[$k]['nick_name']  = "";
                Cache::store('redis')->set('wheat_bit_'.$room_id,$wheat,86400);

                break;
            }
        }

        if ($refresh){
            goto refresh;
        }

        $rows = cache('wheatRequest_1'.$room_id)??[];
        if (in_array($user_id,$rows)){
            unset($rows[$user_id]);
            cache('wheatRequest_1'.$room_id,$rows,todayEndTime());
        }
        $rows = cache('wheatRequest_2'.$room_id)??[];
        if (in_array($user_id,$rows)){
            unset($rows[$user_id]);
            cache('wheatRequest_2'.$room_id,$rows,todayEndTime());
        }
        refresh:
        if($refresh){

            $onlineUser = ChatService::getOnlineCount($room_id);
            //通知到房间热度修改
            self::sendRoomMsg($room_id,'hotChange',['hot'=>hotValue($room_id),'onlineUser'=>$onlineUser]);

        }


        return $refresh;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $room_id =>  房间id
     * @param $data  => 麦序信息
     * 刷新麦序
     */
    public static function refreshWheat($room_id,$refreshPower = false)
    {
        $data = Wheat::wheat($room_id);

        if ($refreshPower){
            foreach ($data as $k => $v){

                if (!is_zero($v['user_id'])){

                    $data[$k]['power'] = getPowerCode($v['user_id'],$room_id,true);
                }
            }
            Wheat::setWheat($room_id,$data);
        }
        self::sendRoomMsg($room_id,'refreshWheat',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 充值回调成功处理
     */
    public function recharge($data,$type = 1)
    {
        $user_id = dehashid($data['user_id']);

        if (!is_numeric($user_id))  return false;

        $map['r_id']   = $data['id'];
        $map['status'] = 1;
        $config = Db::name('recharge_config')->where($map)->cache(3)->find();

        $item['user_id']     = $user_id;
        $item['money']       = $data['money'];
        $item['remark']      = $data['remark'];
        $item['status']      = 1;
        $item['type']        = 1;
        $item['create_time'] = time();
        $item['update_time'] = time();
        $item['trade_type']  = $type;

        $proxy_id = $this->userInfo('proxy_id',$user_id);
        $create_time = $this->userInfo('create_time',$user_id);
        $error['user_id'] = $user_id;
        $error['data'] = $data;
        $error['proxy_id'] = $proxy_id;
        Log::write($error,'xiaosong');
        if ($proxy_id && (time() - $create_time) <= (86400 * 31)){

            $jewel = self::getExtend('jewel');
            $ratio = $jewel/100;
            $item['jewel']       = $config['money'] * $ratio;
            $title = sprintf('推荐新用户充值%s钻获得返利%s钻[%s]',$config['money'],$item['jewel'],$jewel.'%');
            money_detail(1,$proxy_id,$title,$item['jewel'],'锁定');
            Db::name('users')->where('user_id',$proxy_id)->setInc('spread_total',$item['jewel']);
            Db::name('users')->where('user_id',$proxy_id)->setInc('spread_cash',$item['jewel']);
            self::sendUsrMsg('system',hashid($proxy_id),$title);

        }else{
            $item['jewel']  = 0;
        }

        Db::name('bankroll')->strict(false)->insert($item);

        money_detail(1,$user_id,'充值'.$config['money'].'钻',$config['money'],'充值');
//        $phone = $this->userInfo('phone',$user_id);
//        $val['val1'] = substr($phone,-4,4);
//        $val['val2'] = $config['money'];

        $str = sprintf('您已成功充值%s钻，本次充值赠送了%s金币赶快进入App使用吧！如有疑问请及时与我们联系。',$config['money'],$config['give']);
        self::sendUsrMsg('system',hashid($user_id),$str);
//        sendCustomSms($phone,$val,'recharge');
        //砸蛋活动开启时赠送锤子
//        $info = self::getExplain('giveOpen,givePrice');
//        if ($info['giveOpen'] === 'open'){
//            $num = bcdiv($config['money'],$info['givePrice'],0);
//            if ($num > 0){
//                Db::name('users')->where('user_id',$user_id)->setInc('hammer_give',$num);
//                $str = sprintf('本次充值赠送了%s个锤子,赶快进入砸蛋活动使用吧!',$num);
//                self::sendUsrMsg('system',hashid($user_id),$str);
//            }
//        }
        Db::name('users')->where('user_id',$user_id)->setInc('coin',$config['give']);
        return Db::name('users')->where('user_id',$user_id)->setInc('money',$config['money']);
    }



    public function _empty()
    {
        api_return(0,'路由错误');
    }

    protected function phone_to_id(){
        $phone = input('post.phone');
        $usr = Db::name('users')->where(['phone'=>$phone,'status'=>1])->value('user_id');
        if(!$usr||is_null($usr)){
            api_return(0,'用户信息不存在或被禁用');
        }
        return $usr;
    }



    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 创建token 并存储在缓存中
     */
    protected function makeToken($user_id){
        $hash  = hashid($user_id);
        $key   = md5($user_id.time());
        $token = $hash.'+'.$key;


        $cache['key']     = $key;
        $cache['user_id'] = $user_id;

        cache('token_'.$hash,$cache,time()+config('token_expire'));

        return $token;
    }

    protected static function updateUserExtend($user_id,$data = null){

        if (!is_array($data)){
            $data = \request()->only(
                ['log','lat','place','j_push_id','invite','dispatch','filter','hall','wx_name','qq_name','wb_name','LabourUnion']
                ,'post');
        }

        $validate = new \app\common\validate\Base();

        if (!$validate->scene('edit_extend')->check($data)){
            api_return(0,$validate->getError());
        }

        $result = Db::name('user_extend')->where('user_id',$user_id)->update($data);
        if ($result === false){
            //如果更新失败就重复更新一次
            return Db::name('user_extend')->where('user_id',$user_id)->update($data);
        }
        return $result;
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 增加用户经验
     */
    protected function addLevel($experience = 0,$user_id = null)
    {

        if (!$experience) return;
        if (!$user_id){
            $user_id = $this->user_id;
        }

        $extra = $this->userExtra('noble_id,noble_time,user_id',$user_id);

        $noble_id = self::checkNoble($extra);

        if ($noble_id != 0){
            $speed = Db::name('noble')->where('noble_id',$noble_id)->value('speed')??1;
        }else{
            $speed = 1;
        }

        $experience = bcmul($speed,$experience,0);

        $nowLevel = $this->userExtra('level',$user_id);
        $nowExperience = $this->userExtra('experience',$user_id);
        $data = $this->nextLevel($nowLevel,$nowExperience);

        $item['experience'] = bcadd($experience,$nowExperience,0);

        if ($experience >= $data['nextExperience']){
            $maxLevel = Db::name('user_level')->order('level desc')->cache(30)->value('level');

            if ($nowLevel < $maxLevel){
                //达到等级升级经验且当前等级小于最大等级更新大厅VIP等级

                $level = $this->levelNum($item['experience'],$nowLevel);

                if ($level){
                    $item['level'] = $level;
                }
            }
        }
        $result = Db::name('user_extend')->where('user_id',$user_id)->update($item);
        if ($result === false){
            api_return(0,'增加经验失败!');
        }
        return true;
    }

    /**
     * token对比
     * 用于验证是否登陆
     */
    protected function checkToken(){
        $request = Request::instance();
        if ($request->isPost()){
            $token = $request->post('token')??$request->header()['token'];
            if (empty($token)){
                api_return(-1,'未登录');
            }

            $data = explode('+',$token);
            $cache = cache('token_'.$data[0]);
            if ($cache && $cache['key'] == $data[1] && is_numeric(dehashid($data[0]))){

                return $cache['user_id'];
            }else{
                api_return(-1,'登录过期');
            }
        }
        api_return(0,'访问错误');
    }

    /**
     * 非强制登录情况下获取用户id
     * 用于验证是否登陆
     */
    protected static function getUserId($token = null){

        if (!$token){
            $token = request()->post('token')??request()->header()['token'];
            if (empty($token)){
                return 0;
            }
        }

        $data = explode('+',$token);
        //TODO 上线后删除该行代码
        $cache = cache('token_'.$data[0]);

        if ($cache && $cache['key'] == $data[1]){
            return $cache['user_id'];
        }else{
            return 0;
        }

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取与当前用户相反的性别数字
     */
    protected function getSex($user_id = 0){
        if ($this->userInfo('sex',$user_id) == 1){
            return 2;
        }else{
            return 1;
        }
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 检查验证码是否正确
     */
    protected function checkCode($field = 'phone',$msg = '验证码错误',$code = 'code')
    {
        if (is_numeric($field)){
            $phone = $field;
        }else{
            $phone = input("post.$field");
        }
        $code  = input("post.$code");
        if(false){//2019-9-5 hawk 临时切换短信校核，正式待xiaosong调整
            $res = checkMobSms($phone,$code);
            if (!$res)api_return(0,$msg);
        }
        $cache = cache('code'.$phone);
        if (!$cache || $code != $cache){
            //TODO 上线后解开注释
//            api_return(0,$msg);
        }else{
            cache('code'.$phone,null);
        }
    }



    /**
     * @param int $phone
     * @return bool
     * 检查手机号是否可以注册
     */
    protected function is_register($phone = 0)
    {
        $data   = Db::name('users')->where('phone',$phone)->value('user_id');
        if ($data) return false;
        return true;
    }

    /**
     * 验证昵称是否可用
     */
    protected function exist($nick_name){
        $data  = Db::name('users')->where('nick_name',$nick_name)->value('user_id');
        if ($data){
            return false;
        }else{
            $arr = Db::name('extend')->where('id',1)->value('nick_name');
            $array = explode(',',$arr);
            if (in_array($nick_name,$array)){
                return false;
            }
        }
        return true;
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 查询单独一条数据
     * @param string $db 要操作的数据库
     * @param string|array $map 传入string为单字段筛选根据post获取到的id进行查找  传入array即代表调用方法前已处理数据 直接筛选
     * @param string $field 要查找的数据字段
     * @param bool $type 为false表示查找$field字段 为true表示过滤$field字段
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _find($db = '',$map = '',$field = '', $type = false){
        if (is_array($map)){
            $where = $map;
        }else{
            $id = input('post.id');
            if(is_numeric($id)){
                $where[$map] = $id;
            }else{
                api_return(0,'参数错误');
            }
        }
        return Db::name($db)->field($field,$type)->where($where)->find();
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取单独字段数据
     * @param string $db 要操作的表
     * @param string $field 要获取的字段
     * @param string|array $map 传入string为单字段筛选根据post获取到的id进行查找  传入array即代表调用方法前已处理数据直接查找
     * @return mixed
     */
    protected function _value($db = '',$field = '',$map = ''){
        if (is_array($map)){
            $where = $map;
        }else{
            $id = input('post.id');
            if(is_numeric($id)){
                $where[$map] = $id;
            }else{
                api_return(0,'参数错误');
            }
        }
        return Db::name($db)->where($where)->value($field);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 修改数据
     */
    public function _edit($table = '',$validate = true,$data = null)
    {

        if (!$data){
            $data = input('post.');
        }
        $model = new Logic();
        $result = $model->saveChange($table,$data,$validate);
        if ($result !== false){
            return true;
        }
        $this->editError = $model->getError();
        return false;
    }

    protected $editError = '系统繁忙,请稍后重试';

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 数据删除
     * @param string $db 要进行操作的数据库
     * @param string $field 要操作的字段名
     * @param bool $type false 假删 true 真删
     * @return int|string
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    protected function _pass($db = '',$field = '',$type = false){
        $id = input('post.id');
        if(is_numeric($id)){
            if ($type){
                return Db::name($db)->where($field,$id)->delete();
            }else{
                return Db::name($db)->where($field,$id)->update(['status' => 0]);
            }
        }
        api_return(0,'参数错误');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * @param string $user_id
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取融云token
     */
    protected function R_token($user_id = '')
    {

        //$token  = cache('r_token_'.$user_id);
        //if ($token) return $token;
        $userId     = hashid($user_id);
        $userInfo   = Db::name('users')->where('user_id',$user_id)->field('nick_name,header_img')->find();
        $nick_name  = $userInfo['nick_name']??'游客'.rand(111111,99999);
        $header_img = $userInfo['header_img']??App::getExtend('default_img');

        $model  = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $model->user()->getToken($userId,$nick_name,$header_img);
        $res    = json_decode($result,true);
        if ($res['code'] == 200){
            if (is_numeric($user_id)) cache('r_token_'.$user_id,$res['token'],86400*7);
            return $res['token'];
        }
        return "";
    }

    /**
     * 获取用户已装备头像
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $value
     * @param $data
     */
    public static function getHeadWear(int $user_id)
    {
        $map['user_id']  = $user_id;
        $map['end_time'] = [['>',time()],['=',0],'or'];
        $map['type']     = 2;
        $map['is_use']   = 1;
        $map['status']   = 1;

        $my = MyCar::where($map)->find();

        if ($my){
            $uri = \app\common\model\Car::where('car_id',$my['car_id'])->value('thumbnail');
        }else{
            $uri = '';
        }
        return $uri;
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据表主键修改单字段状态

     */
    protected function _changeField(string $table,int $pk,$field = 'status',$update = 0){
        $db = Db::name($table);
        return $db->where($db->getPk(),$pk)->update([$field=>$update]);
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户信息
     */
    public function userInfo($field = '',$user_id = 0,$cache = 3){

        if ($user_id){

            $map['user_id'] = $user_id;

        }else{

            $map['user_id'] = $this->user_id;

        }
        $data =  Db::name('users')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * @param $user_id
     * 登录日志
     */
    public function log($user_id,$model = '')
    {

        //登陆日志
        $log['ip'] = request()->ip();
        if (empty(input('post.model'))){
            $log['model'] = 'web';
        }else{
            $log['model'] = input('post.model');
        }

        $log['user_id'] = $user_id;
        $log['create_time'] = time();
        Db::name('login_log')->insert($log);
    }

    /**
     * @param $room_id string  要发送到的聊天室id
     * @param $type   int  消息类型 详见switch注释
     * @param $rows  array 消息主体内容
     *
     *  $rows 解释
     *  gift  礼物消息
     *  $rows[gift_name]  礼物名称
     *  $rows[img]  礼物图片地址
     *  $rows[num]  送礼数量
     *  $rows[role_name]  送礼者角色名
     *  $rows[role_id]  送礼者加密后角色id
     *
     *
     *  red_package 红包消息
     *  $rows[msg]  红包信息
     *  $rows[red_id]  红包id
     *  $rows[role_name]  发送者角色名
     *  $rows[header_img]  发送者头像
     *  $rows[role_id]  发送者加密后角色id
     *
     *
     * guess 竞猜消息
     * $rows['guess_id'] 竞猜id
     * $rows['title']  竞猜标题
     * $rows['answer_A']  选项A
     * $rows['answer_B']  选项B
     *
     *融云自定义消息房间消息发送
     */
    public function sendRoomMsg($room_id,$type,$rows = []){

        $model = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);

        if ($room_id == 'all'){
            $room_ids = Db::name('room')->where('status',1)->cache(300)->column('room_id');
        }else{
            $room_ids = [$room_id];
        }

//        $content = json_encode(['content'=>$rows,'extra'=>$type]);

//        return $model->message()->publishChatroom('system',$room_ids, 'RC:system',$content);

//        $model = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $data['type'] = $type;//礼物消息
        $data['data'] = $rows;

        $content = json_encode(['content'=>$data,'extra'=>'']);
        return $model->message()->publishChatroom('system', $room_ids, 'RC:system',$content);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $user_id =>接收消息用户
     * @param $type
     * @param array $rows
     * @return mixed
     * 融云自定义用户消息发送
     */
    public static function sendUsrMsg($fromUser,$user_id,$content = [],$extra = ['type'=>'text','data'=>null]){
        $model = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $content = json_encode(['content'=>$content,'extra'=>$extra]);
        if (!is_array($user_id)){
            $user_id = [$user_id];
        }
        return $model->message()->publishPrivate($fromUser,$user_id,'RC:TxtMsg',$content, 'thisisapush', '{\"pushData\":\"hello\"}', '4', '0', '0', '0', '0');
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 技能统计
     */
    protected static function orderCount(array $map) :array
    {

        $data['num'] = Db::name('order')->where($map)->cache(10)->count('order_id');

        $score = Db::name('order')->where($map)->cache(10)->avg('score');

        $data['score'] = numberDecimal($score);

        return $data;
    }




    /**
     * 房间禁言名单获取
     */
    protected function banList($room_id)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result    =  $RongCloud->group()->lisGagUser($room_id);
        $json = json_decode($result,true);
        if ($json['code'] == 200)

            return $json['users'];
        return false;
    }

    /**
     * 禁言
     */
    protected function ban($room_id,$role_id,$time = 10)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $RongCloud->group()->addGagUser($role_id, $room_id, $time);
        $json = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }
    
    
    /**
     * 解除禁言
     */
    public function pick($role_id,$room_id)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $RongCloud->group()->rollBackGagUser([$role_id], $room_id);
        $json = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }

    /**
     * 聊天室禁言
     */
    protected function chatban($room_id,$role_id,$time = 10)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $RongCloud->chatRoom()->addGagUser($role_id, $room_id, $time);
        $json = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }

    /**
     * 聊天室禁言名单获取|检查某个用户在当前房间是否被禁言
     */
    protected function chatbanList($room_id,$user_id = 0)
    {
        if ($user_id){
            if (is_numeric($user_id)) $user_id = hashid($user_id);
            $cache = cache('chat_'.$room_id.'_'.$user_id);
            if ($cache) return $cache;
        }else{
            $cache = cache('banlist_'.$room_id);
            if ($cache) return $cache;
        }
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result    =  $RongCloud->chatRoom()->ListGagUser($room_id);
        $json = json_decode($result,true);
        if ($json['code'] == 200){
            if ($user_id){
                $rows = array_key($json['users'],'userId');
                $data = isset($rows[$user_id]);
                cache('chat_'.$room_id.'_'.$user_id,$data,5);
                return $data;
            }
            cache('banlist_'.$room_id,$json['users'],5);
            return $json['users'];
        }
        return false;
    }


    /**
     * 聊天室解除禁言
     */
    public function chatpick($role_id,$room_id)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $RongCloud->chatRoom()->rollBackGagUser([$role_id], $room_id);
        $json = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 接口单独限流
     */
    protected function ApiLimit($time = 1,$id = 0,$msg = '请求过于频繁,请稍后重试')
    {
        $key   = request()->path().$id;
        $cache = cache('apiLimit'.$key);
        if ($cache){
            api_return(0,$msg);
        }else{
            cache('apiLimit'.$key,1,$time);
        }
    }

    /**
     * @param int $id
     * 销毁限流参数
     */
    protected function destroyLimit($id = 0){
        $key   = request()->path().$id;
        cache('apiLimit'.$key,null);

    }




    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 推送
     * @param $type 1 房间 2 资产 3钱包
     * @param string $j_push_id
     * @param string $title
     * @param $room_id
     * @return bool
     *
     */
    protected function Push($type,$j_push_id = '',$title = '来自哈尼直播的推送消息',$room_id)
    {
        if (!$j_push_id) return false;

        $extend = [];
        if ($type == 1){
            $extend['extras'] = [
                'type' => 'room',//跳转至房间
                'room_id' => $room_id,
            ] ;
        }elseif ($type == 2){
            $extend['extras'] = [
                'type' => 'assets',//跳转至资产
            ] ;
        }elseif ($type == 3){
            $extend['extras'] = [
                'type' => 'wallet',//跳转至钱包
            ] ;
        }

         j_push($title,$j_push_id,$extend);
        dump($extend);exit;
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取系统扩展信息
     */
    protected function extend($field = '',$cache = 15){

        $data =  Db::name('extend')->where('id',1)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr   = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    public static function getExtend($field = '',$cache = 15){

        $data =  Db::name('extend')->where('id',1)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr   = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 礼物赠送
     */
    protected  function giveGift(array $data,$user_id = null ) :array
    {
        if (!$user_id){
            $user_id = $this->user_id;
        }

        $map['gift_id'] = $data['id'];
//        $map['status']  = 1;

        $gift = Db::name('gift')->where($map)->find();

        if (!$gift || $gift['price'] <= 0 ) api_return(0,'参数错误');

        if (!isInt($data['num'])) api_return(0,'赠送数量错误');

        if (empty($data['to_user'])) api_return(0,'请选择要赠送的的人');

        //获取要赠送的人数
        $people = count(explode(',',$data['to_user']));

        //根据人数及每人赠送数量判断赠送总数
        $total = bcmul($gift['price'],$data['num'],2);

        if ($total <= 0) api_return(0,'赠送金额错误');

        $price = bcmul($total,$people,2);

        $subject = '哈尼礼物('.$gift['gift_name'].')赠送';
        $array = [
            'subject' => $subject,
            'user_id' => hashid($user_id),
            'id' => $data['id'],
            'type' => $data['type'],
            'to_user' => $data['to_user'],
            'room_id' => $data['room_id']??0,
            'total' => $total,
            'price' => $price,
            'num' => $data['num'],
            'gift_type' => $gift['type'],
            'allNum'    => $people * $data['num'],//所有礼物总数
            'onePrice'  => $gift['price'],//单个礼物价格
            'countInfo' => $data['countInfo'],
        ];

        return $array;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单退款
     */
    public static function refund($data,$status = 6){


        if (is_numeric($data)){
            $data = Db::name('order')->where('order_id',$data)->find();
        }

        $array = [1,2,3,7,9];

        if (!in_array($data['status'],$array)){
            return '订单状态不允许退款';
        }

        switch ($data['pay_way']){

            case 1: //积分

                Db::name('users')->where('user_id',$data['user_id'])->setInc('money',$data['price']);

                money_detail(1,$data['user_id'],'订单退款',$data['price'],'退款');

                break;
            case 2://支付宝

                $order = [
                    'out_trade_no' => $data['trade_no'],
                    'refund_amount' => $data['out_price'],
                ];

                $result =  Pays::aliRefund($order);

                if (!$result){
                    return Pays::$errorMsg;
                }

                break;
            case 3://微信
                $order = [
                    'out_trade_no' => $data['trade_no'],
                    'out_refund_no' => $data['out_trade_no'],
                    'total_fee' => $data['out_price']*100,
                    'refund_fee' => $data['out_price']*100,
                    'refund_desc' => '订单退款',
                ];
                Pays::weChatRefund($order);
                break;
            default:
                return '无此支付方式';
                break;

        }

        Db::name('order')->where('order_id',$data['order_id'])->update(['status'=>$status]);

        return true;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单完成
     */
    public static function complete($order)
    {
        //邀约抽成比例
        $invite = self::extend('invite_ratio')??1;

        $ratio = $invite/100;

        //抽成后订单金额
        $money = bcsub($order['price'],bcmul($order['price'],$ratio,2),2);

        $nick_name = self::staticInfo('nick_name',$order['user_id']);

        $skill_name = Db::name('skill')->where('skill_id',$order['skill_id'])->cache(300)->value('skill_name');

        Db::startTrans();
        try{

            Db::name('users')->where('user_id',$order['to_user'])->setInc('cash',$money);
            money_detail(1,$order['to_user'],'和 '.$nick_name.' '.$skill_name.' 完成',$money,'解锁',4,$order['order_id']);

            $where['skill_id'] = $order['skill_id'];
            $where['user_id'] = $order['to_user'];
            Db::name('skill_apply')->where($where)->setInc('num');
            Db::name('order')->where('order_id',$order['order_id'])->update(['status'=>4,'update_time'=>time()]);

            skillFormUser($order);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $e->getMessage();
        }
        return true;
    }




}
